package cn.elwy.rcp.ui.table.internal;

import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;

/**
 * 表格树列排序
 * 
 * @author huangsq
 * @version 1.0, 2014-01-08
 * @since 1.0, 2014-01-08
 */
public class TableColumnSortListener extends SelectionAdapter {

  private ColumnViewer viewer;
  private IBaseLabelProvider labelProvider;

  public TableColumnSortListener(ColumnViewer viewer) {
    this.viewer = viewer;
    labelProvider = viewer.getLabelProvider();
  }

  @Override
  public void widgetSelected(SelectionEvent e) {
    ColumnSorter sorter = (ColumnSorter) viewer.getSorter();
    if (sorter == null) {
      sorter = new ColumnSorter(labelProvider);
      viewer.setSorter(sorter);
    }
    if (e.widget instanceof TableColumn) {
      TableColumn column = (TableColumn) e.widget;
      Table table = ((TableViewer) viewer).getTable();
      int columnIndex = table.indexOf(column);
      sorter.setColumnIndex(columnIndex);
      table.setSortColumn(column);
      table.setSortDirection(sorter.isAscend() ? SWT.DOWN : SWT.UP);
    } else {
      TreeColumn column = (TreeColumn) e.widget;
      Tree tree = ((TreeViewer) viewer).getTree();
      int columnIndex = tree.indexOf(column);
      sorter.setColumnIndex(columnIndex);
      tree.setSortColumn(column);
      tree.setSortDirection(sorter.isAscend() ? SWT.DOWN : SWT.UP);
    }
    viewer.refresh();
  }

}
